"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.autoUpdaterService = exports.AutoUpdaterService = void 0;
const electron_1 = require("electron");
const electron_updater_1 = require("electron-updater");
const utils_1 = require("ee-core/utils");
const log_1 = require("ee-core/log");
const electron_2 = require("ee-core/electron");
/**
 * AutoUpdaterService class for automatic updates
 */
class AutoUpdaterService {
    constructor() {
        Object.defineProperty(this, "config", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
        this.config = {
            windows: false,
            macOS: false,
            linux: false,
            options: {
                provider: 'generic',
                url: 'http://kodo.qiniu.com/'
            },
        };
    }
    /**
     * Create and configure the auto updater
     */
    create() {
        log_1.logger.info('[autoUpdater] load');
        const cfg = this.config;
        if ((utils_1.is.windows() && cfg.windows) ||
            (utils_1.is.macOS() && cfg.macOS) ||
            (utils_1.is.linux() && cfg.linux)) {
            // continue
        }
        else {
            return;
        }
        const status = {
            error: -1,
            available: 1,
            noAvailable: 2,
            downloading: 3,
            downloaded: 4,
        };
        const version = electron_1.app.getVersion();
        log_1.logger.info('[autoUpdater] current version: ', version);
        // Set the download server address
        let server = cfg.options.url;
        const lastChar = server.substring(server.length - 1);
        server = lastChar === '/' ? server : server + "/";
        cfg.options.url = server;
        try {
            electron_updater_1.autoUpdater.setFeedURL(cfg.options);
        }
        catch (error) {
            log_1.logger.error('[autoUpdater] setFeedURL error : ', error);
        }
        electron_updater_1.autoUpdater.on('checking-for-update', () => {
            // sendStatusToWindow('正在检查更新...');
        });
        electron_updater_1.autoUpdater.on('update-available', () => {
            const data = {
                status: status.available,
                desc: '有可用更新',
            };
            this.sendStatusToWindow(data);
        });
        electron_updater_1.autoUpdater.on('update-not-available', () => {
            const data = {
                status: status.noAvailable,
                desc: '没有可用更新',
            };
            this.sendStatusToWindow(data);
        });
        electron_updater_1.autoUpdater.on('error', (err) => {
            const data = {
                status: status.error,
                desc: err,
            };
            this.sendStatusToWindow(data);
        });
        electron_updater_1.autoUpdater.on('download-progress', (progressObj) => {
            const percentNumber = progressObj.percent;
            const totalSize = this.bytesChange(progressObj.total);
            const transferredSize = this.bytesChange(progressObj.transferred);
            let text = '已下载 ' + percentNumber + '%';
            text = text + ' (' + transferredSize + "/" + totalSize + ')';
            const data = {
                status: status.downloading,
                desc: text,
                percentNumber,
                totalSize,
                transferredSize,
            };
            log_1.logger.info('[addon:autoUpdater] progress: ', text);
            this.sendStatusToWindow(data);
        });
        electron_updater_1.autoUpdater.on('update-downloaded', () => {
            const data = {
                status: status.downloaded,
                desc: '下载完成',
            };
            this.sendStatusToWindow(data);
            // Allow the window to close
            (0, electron_2.setCloseAndQuit)(true);
            // Install updates and exit the application
            electron_updater_1.autoUpdater.quitAndInstall();
        });
    }
    /**
     * Check for updates
     */
    checkUpdate() {
        electron_updater_1.autoUpdater.checkForUpdates();
    }
    /**
     * Download updates
     */
    download() {
        electron_updater_1.autoUpdater.downloadUpdate();
    }
    /**
     * Send status to the frontend
     */
    sendStatusToWindow(content = {}) {
        const textJson = JSON.stringify(content);
        const channel = 'custom/app/updater';
        const win = (0, electron_2.getMainWindow)();
        win.webContents.send(channel, textJson);
    }
    /**
     * Convert bytes to a more readable format
     */
    bytesChange(limit) {
        let size = "";
        if (limit < 0.1 * 1024) {
            size = limit.toFixed(2) + "B";
        }
        else if (limit < 0.1 * 1024 * 1024) {
            size = (limit / 1024).toFixed(2) + "KB";
        }
        else if (limit < 0.1 * 1024 * 1024 * 1024) {
            size = (limit / (1024 * 1024)).toFixed(2) + "MB";
        }
        else {
            size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
        }
        let sizeStr = size + "";
        let index = sizeStr.indexOf(".");
        let dou = sizeStr.substring(index + 1, index + 3);
        if (dou === "00") {
            return sizeStr.substring(0, index) + sizeStr.substring(index + 3, index + 5);
        }
        return size;
    }
}
exports.AutoUpdaterService = AutoUpdaterService;
AutoUpdaterService.toString = () => '[class AutoUpdaterService]';
const autoUpdaterService = new AutoUpdaterService();
exports.autoUpdaterService = autoUpdaterService;
